import peewee_async
from base import BaseHandler # 用户模块
from db import User_Model,CheckNum_Model,Node_Model,Access_Model,Role_Model,User_Role_Model,Access_role_Model  # 导入用户模型类
from tornado.web import url  # 导入torando路由
from utils import create_code,EmailTool,MyJwt,MyFile,jwt_token,WriteFile,Upyun,Page,acl_auth,rbac_auth
from werkzeug.security import check_password_hash,generate_password_hash
from PIL import ImageDraw,Image,ImageFont # 绘制图片   图片  字体
import re # 正则
import hashlib # 加密
import io
import random
import time
import requests
from db import database
import json
import os
from functools import wraps
from abc import ABCMeta,abstractmethod
from playhouse.shortcuts import model_to_dict     # 序列化


# 角色
class RoleHandler(BaseHandler):
    @jwt_token
    async def post(self):
        rid = self.get_argument('rid',None)
        checked = self.get_argument('checked', None)
        checked = json.loads(checked)
        role_list = await self.application.objects.execute(
            Access_role_Model.select().where(Access_role_Model.rid == rid))
        for x in role_list:
            await self.application.objects.delete(x)
        for i in checked:
            try:
                await self.application.objects.create(Access_role_Model, rid=rid, nid=i)
            except Exception as e:
                pass
        return self.finish({'errcode': 0, 'msg': '修改角色权限成功'})

    @jwt_token
    async def delete(self):
        rid = self.get_argument('rid',None)
        role_list = await self.application.objects.execute(
            Access_role_Model.select().where(Access_role_Model.rid == rid))
        temp = []
        for x in role_list:
            temp.append(x.nid)
        node_list = temp
        return self.finish({'errcode':0,'msg':'获取角色节点成功','data':node_list})

    @jwt_token
    async def put(self):    # 修改角色分组
        checked = self.get_argument('checked', None)
        checked = json.loads(checked)
        role_list = await self.application.objects.execute(
            User_Role_Model.select().where(User_Role_Model.uid == self._cuser.id))
        for x in role_list:
            await self.application.objects.delete(x)
        for i in checked:
            try:
                await self.application.objects.create(User_Role_Model, uid=self._cuser.id, rid=i)
            except Exception as e:
                pass
        return self.finish({'errcode': 0, 'msg': '修改角色成功'})

    @jwt_token
    async def get(self):
        cate = self.get_argument('cate', None)
        optionlist = [] # 用来存放该用户的角色id
        if cate:  # 获取我的权限
            role_list = await self.application.objects.execute(
                User_Role_Model.select().where(User_Role_Model.uid == self._cuser.id))
            temp = []
            for x in role_list:
                temp.append(x.rid)
            role_list = temp
        else:  # 获取全部的权限
            role_list = await self.application.objects.execute(Role_Model.select())
            for x in role_list:
                optionlist.append({'text':x.name,'value':x.id})
            role_list = [model_to_dict(x) for x in role_list]
        return self.finish({'errcode': 0, 'msg': '获取角色成功', 'data': role_list,'option':optionlist})

# 权限接口
class AccessHandler(BaseHandler):


    @jwt_token
    async def put(self):    # 修改权限
        checked = self.get_argument('checked', None)
        checked = json.loads(checked)
        node_list = await self.application.objects.execute(
            Access_Model.select().where(Access_Model.uid == self._cuser.id))
        for x in node_list:
            await self.application.objects.delete(x)
        for i in checked:
            try:
                await self.application.objects.create(Access_Model, uid=self._cuser.id, nid=i)
            except Exception as e:
                pass
        return self.finish({'errcode': 0, 'msg': '修改权限成功'})

# 节点接口
class NodeHandler(BaseHandler):
    @jwt_token
    async def get(self):
        cate = self.get_argument('cate',None)
        if cate:    # 获取我的权限
            node_list = await self.application.objects.execute(Access_Model.select().where(Access_Model.uid==self._cuser.id))
            temp = []
            for x in node_list:
                temp.append(x.nid)
            node_list = temp
        else:     # 获取全部的权限
            node_list = await self.application.objects.execute(Node_Model.select())
            node_list = [model_to_dict(x) for x in  node_list]
        return self.finish({'errcode': 0, 'msg': '获取节点成功', 'data':  node_list})
# 用户管理
class UserManage(BaseHandler):


    @jwt_token
    # @acl_auth()
    @rbac_auth
    async def get(self):  # 获取所有用户信息 （包括查询，分页，排序）
        page = int(self.get_argument('page', 1))  # 当前页
        size = int(self.get_argument('size', 2))  # 一页展示多少个
        newfields = self.get_argument('fields', None)  # 搜索的字段
        keyword = self.get_argument('keyword',None) # 搜索的关键字
        od = self.get_argument('od',None)
        # userlist = await self.application.objects.execute(User_Model.select().paginate(page, size))
        pg = Page(size)
        total = await pg.get_total_page(User_Model,keyword,newfields)   # 获取总页数
        userlist = await pg.get_list(page,User_Model,'user_tb',keyword,newfields,od)  # 获取每页的数据
        userlist = [model_to_dict(i) for i in userlist]
        self.finish({'errcode': 0, 'data': userlist, 'msg': '获取分页数据成功','total':total})


    @jwt_token
    # @acl_auth()
    @rbac_auth
    async def put(self):
        id = self.get_argument('id',None)
        state = self.get_argument('state',None)
        user = await self.application.objects.get(User_Model.select().where(User_Model.id==id))
        user.state = state
        await self.application.objects.update(user)
        return self.finish({'errcode':0,'msg':'修改成功'})

    @jwt_token
    # @acl_auth()
    @rbac_auth
    async def delete(self):
        checked = self.get_argument('checked',None)
        checked = json.loads(checked)
        for x in checked:
            user = await self.application.objects.get(User_Model, id=x)
            await self.application.objects.delete(user)
        return self.finish({'errcode': 0, 'msg': '删除成功'})




# 文件控制接口
class FileHandler(BaseHandler):
    @jwt_token       # 本地版本
    async def get(self):
        uid = self._cuser.id
        files = WriteFile(uid).filelist()
        filelist = []
        for x in files:
            item = {
                'filename': x,
                'tag':WriteFile(uid).filetype(x),
            }
            filelist.append(item)
        return self.finish({'errcode': 0, 'data': filelist, 'msg': '获取文件成功'})

    @jwt_token
    async def delete(self):
        uid = self._cuser.id
        filename = self.get_argument('filename')  # 想要删除的文件列表
        for i in json.loads(filename):
            WriteFile(uid).del_file(i)
            Upyun(uid).delfile(i)  # upyun 删除
        return self.finish({'errcode': 0, 'msg': '文件删除成功'})
    # @jwt_token
    # async def get(self):
    #     print(123)
    #     uid = self._cuser.id
    #     files = Upyun(uid).filelist()
    #     filelist = []
    #     for x in files:
    #         item = {
    #             'filename': x['name'],
    #             'tag':Upyun(uid).filetype(x['name'])
    #         }
    #         filelist.append(item)
    #     return self.finish({'errcode': 0, 'data': filelist, 'msg': '获取文件成功'})
    #
    # @jwt_token
    # async def delete(self):
    #     uid = self._cuser.id
    #     filename = self.get_argument('filename')
    #
    #     for i in json.loads(filename):
    #         Upyun(uid).delfile(i)  # upyun 删除
    #     return self.finish({'errcode': 0, 'msg': '文件删除成功'})

# 上传文件
class FileUpload(BaseHandler):
    @jwt_token      # 本地版本
    async def post(self):
        # print(self.get_argument('file'))
        # 接受文件实体
        file = self.request.files['file']   # 是一个列表
        upload = self.get_argument('upload','0')  # 0 上传文件  1上传头像

        # 遍历文件
        # for meta in file:
        meta = file[0]       # meta['filename']文件名   meta['body'] 文件流
        # 创建目录
        WriteFile(self._cuser.id).createfile()
        filepath = './static/user%s/'%self._cuser.id  + meta['filename']
        with open(filepath, 'wb')as f:
            f.write(meta['body'])
        Upyun(self._cuser.id).upload(meta['filename'])  # 创建目录并上传到upyun
        # 判断上传文件的类型
        if int(upload) == 1:    # 是否为修改头像
            self._cuser.avtar = filepath
            await self.application.objects.update(self._cuser)

        return self.finish({'errcode':0,'msg':'文件上传成功','filepath':filepath,'filename':meta['filename']})

    # @jwt_token
    # async def post(self):
    #     # print(self.get_argument('file'))
    #     # 接受文件实体
    #     file = self.request.files['file']  # 是一个列表
    #     upload = self.get_argument('upload', '0')  # 0 上传文件  1上传头像
    #     meta = file[0]
    #     try:
    #         filepath = Upyun(self._cuser.id).create_file(meta['filename'],meta['body'])  # 上传到upyun
    #     except Exception as e:
    #         print(e)
    #         return self.finish({'errcode': 1, 'msg': '文件上传失败'})
    #     if int(upload) == 1:
    #         self._cuser.avtar = filepath
    #         await self.application.objects.update(self._cuser)
    #
    #     return self.finish({'errcode': 0, 'msg': '文件上传成功', 'filepath': filepath, 'filename': meta['filename']})





# 工厂类
class SimpleFactory:
    @staticmethod
    def product(name):
        if name == 'sina':
            return SinlangProvider()
        elif name == 'gitee':
            return GiteeProvider()

# 抽象类  三方登录抽象类
class IdProvider(metaclass=ABCMeta):     # 我的理解  就是定义一个类的框架 方法与参数写死 然后功能类按照要求实现功能即可

    # 生成跳转url
    @abstractmethod  # 声明抽象方法
    def get_url(self):
        pass
    #
    # 获取token
    @abstractmethod
    def get_token(self,code):
        pass
    #
    # 获取用户信息
    @abstractmethod
    def get_user(self,token,uid):
        pass

    #保存用户信息
    @abstractmethod
    async def save_user(self,user):
        pass


# 图片验证码验证装饰器
def check_imgcode(func):
    @wraps(func)
    async def wrapper(self,*args,**kwargs):
        email = self.get_argument('email', None)
        imgcode = self.get_argument('imgcode', None)
        redis_imgcode = self.application.redis.get(email)  # 获取图片验证码
        print('----', redis_imgcode, imgcode)
        if not redis_imgcode:
            return self.finish({'msg': '图片验证码已过期，请重新获取', 'errcode': '400'})
        if redis_imgcode != imgcode:  # 校验图片验证码
            return self.finish({'msg': '图片验证码错误', 'errcode': '400'})
        await func(self,*args,**kwargs)
    return wrapper

# 图片验证码类
class ImageCode(BaseHandler):
    # 随机颜色实例方法
    def get_random_color(self):
        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)
        return (R,G,B)

    # 生成文件流验正码
    async def get(self):
        email = self.get_argument('email', None)
        if not email:
            return self.finish({'msg':'缺少唯一标识邮箱','errcode':'400'})
        # 定义画布
        img_size = (120,50)
        # 定义画笔                        背景色
        image = Image.new('RGB',img_size,'white')
        draw = ImageDraw.Draw(image,'RGB')

        # 定义字符串
        source = '0123456789'
        # 定义容器
        code_str = ''
        # 循环绘制
        for i in range(4):
            # 获取一种颜色
            text_color = self.get_random_color()
            # 获取随机字符串
            tmp_num = random.randrange(len(source))  # 随机下标
            random_str = source[tmp_num]     # 根据下标获取字符串
            # 收集到容器中
            code_str += random_str
            # 导入系统字体                                                # 字号（大小）
            myfont = ImageFont.truetype('c:\\windows\\fonts\\STKAITI.TTF',20)
            # 绘制       坐标
            draw.text((10+30*i,20),random_str,text_color,font=myfont)    # 按照坐标 将字符串写入图片

        # 存入验证码
        self.application.redis.set(email,code_str,60*2)

        # 获取内容缓冲区
        buf = io.BytesIO()
        # 保存图形对象
        image.save(buf,'png')
        # 设置头部声明
        self.set_header('Content-Type','image/png')
        # 返回
        return self.write(buf.getvalue())

# 密码加密
def make_password(password):

    md5 = hashlib.md5()  # md5
    sign_utf8 = str(password).encode(encoding='utf-8')  # 转码
    md5.update(sign_utf8)   # 加密
    return md5.hexdigest()   # 返回密文

# 验证密码
def is_valpassword(password):
    p = re.match(r'^[a-z,A-Z]\w{5,19}$', password)
    return p

# 验证邮箱
def is_valemail(email):
    e = re.match(r'^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$', email)
    return e

# 注册与激活
class UserHandler(BaseHandler):
    # 声明方法   # 注册
    @check_imgcode
    async def post(self):
        # 接受参数
        email = self.get_argument('email',None)
        password = self.get_argument('password',None)
        # if not all([email,password]):
        #     return self.finish({'msg': '邮箱和密码不能为空', 'errcode': '400'})
        # password = generate_password_hash(password)
        # res = is_valemail(email)  # 验证邮箱
        # if not res:
        #     return self.finish({'msg': '邮箱格式不正确', 'errcode': '400'})
        # res = is_valpassword(password)  # 加密密码
        # if not res:
        #     return self.finish({'msg': '密码字母开头，6-20位', 'errcode': '400'})
        password = make_password(password)  # 密码加密

        try:
        # 异步入库
            await self.application.objects.create(User_Model, email=email,
                                                  password=password,cate=0)
            code = create_code()  # 生成激活码
            print(code)
            # EmailTool().sendemail(email,code)  # 发送激活码
            self.application.redis.set(email, code,60*2)  # 存储激活码
            return self.finish({'msg':'注册成功','errcode':'0'})
        except Exception as e:
            print(e)     # 因为邮箱有唯一约束 所以报错代表添加了重复的邮箱
            return self.finish({'msg': '邮箱已存在', 'errcode': '400'})

    # 激活用户
    async def put(self):
        email = self.get_argument('email', None)
        code = self.get_argument('code', None)
        r_code = self.application.redis.get(email)
        if not r_code:
            return self.finish({'msg': '激活失败，激活码不存在', 'errcode': '400'})
        if r_code == code:
            users = await self.application.objects.get(User_Model, email=email)
            # users = await self.application.objects.get(User_Model.select().where(User_Model.email==email))
            users.state = 1  # 修改状态
            # users.save()   # 保存
            await self.application.objects.update(users)
            return self.finish({'msg': '激活成功', 'errcode': '0'})
        # xcode = create_code()  # 生成新的激活码
        # print('新的',xcode)
        # # EmailTool().sendemail(email,xcode)  # 发送激活码
        # self.application.redis.delete(email)    # 删除旧的
        # self.application.redis.set(email, xcode)  # 存入新的
        return self.finish({'msg': '激活失败，激活码错误', 'errcode': '400'})

# 登录
class UserLogin(BaseHandler):
    # 文件操作 版本
    async def get(self):
        email = self.get_argument('email', None)
        password = self.get_argument('password', None)

        ban_key = 'ban:%s' % email  # 账号封禁30分钟的键
        # key = 'login:%s' % email    # 账号五分钟的错误次数的键
        filename = '%s.txt' % email
        f = MyFile()
        if self.application.redis.get(ban_key):  # 看账号是否被封禁
            return self.finish({'msg': '该账号已被封禁30分钟', 'errcode': '400'})



        try:
            if not f.check(filename):  # 检验文件    # 文件操作版本：
                self.application.redis.set(ban_key, 1, ex=30*60)
                return self.finish({'msg': '登录失败次数过多，30分钟后再试', 'errcode': '400'})  # 文件操作版本：

            user = await self.application.objects.get(User_Model.select().where((User_Model.email==email)    # 验证用户名和密码
                                                                                & (User_Model.password==make_password(password))&(User_Model.cate==0)))
            if user.state == 0:
                return self.finish({'msg': '该邮箱没有激活,请先激活', 'errcode': '402'})
            jwt_token = MyJwt().encode({'id':user.id,'email':user.email})
            return self.finish({'msg': '登录成功', 'errcode': '0', 'email': user.email,'token':jwt_token})

        except Exception as e:

            f.write(filename)  # 写入文件    # 文件操作版本：
            return self.finish({'msg': '账号或密码错误', 'errcode': '400'})   # 文件操作版本：
    # mysql 版本
    # async def get(self):
    #     email = self.get_argument('email', None)
    #     password = self.get_argument('password', None)
    #
    #     ban_key = 'ban:%s' % email  # 账号封禁30分钟的键
    #     # key = 'login:%s' % email    # 账号五分钟的错误次数的键
    #     filename = '%s.txt' % email
    #     f = MyFile()
    #     if self.application.redis.get(ban_key):  # 看账号是否被封禁
    #         return self.finish({'msg': '该账号已被封禁30分钟', 'errcode': '400'})
    #     try:
    #         user = await self.application.objects.get(
    #             User_Model.select().where((User_Model.email == email)  # 验证用户名和密码
    #                                       & (User_Model.password == make_password(password))))
    #         if user.state == 0:
    #             return self.finish({'msg': '该邮箱没有激活,请先激活', 'errcode': '402'})
    #         jwt_token = MyJwt().encode({'id': user.id, 'email': user.email})
    #         return self.finish({'msg': '登录成功', 'errcode': '0', 'email': user.email, 'token': jwt_token})
    #
    #     except Exception as e:
    #         try:  # mysql 版本
    #             num_mysql = await self.application.objects.get(
    #                 CheckNum_Model.select().where(CheckNum_Model.email == email))
    #         except Exception as e:
    #             num_mysql = None
    #         if num_mysql:
    #             # 获取当前时间
    #             now_time = int(time.time())
    #             # 获取首次输错密码的时间
    #             num_time = num_mysql.create_time.timestamp()
    #             my_time = now_time - num_time
    #             print(my_time,num_mysql.num)
    #             if my_time <= 30:
    #                 if num_mysql.num >= 5:
    #                     await self.application.objects.delete(num_mysql)
    #                     self.application.redis.set(ban_key,1,30)
    #                     return self.finish({'msg': '该账号已被封禁30分钟', 'errcode': '400'})
    #                 else:
    #                     num_mysql.num = num_mysql.num + 1
    #                     await self.application.objects.update(num_mysql)
    #             else:
    #                 # 清除计时器
    #                 await self.application.objects.delete(num_mysql)
    #         else:
    #             await self.application.objects.create(CheckNum_Model,email=email,num=1)
    #         return self.finish({'msg': '账号或密码错误', 'errcode': '400'})
        # redis 版本
        # async def get(self):
        #     email = self.get_argument('email', None)
        #     password = self.get_argument('password', None)
        #
        #     ban_key = 'ban:%s' % email  # 账号封禁30分钟的键
        #     key = 'login:%s' % email    # 账号五分钟的错误次数的键
        #
        #     if self.application.redis.get(ban_key):  # 看账号是否被封禁
        #         return self.finish({'msg': '该账号已被封禁30分钟', 'errcode': '400'})
        #     try:
        #         user = await self.application.objects.get(
        #             User_Model.select().where((User_Model.email == email)  # 验证用户名和密码
        #                                       & (User_Model.password == make_password(password))))
        #         if user.state == 0:
        #             return self.finish({'msg': '该邮箱没有激活,请先激活', 'errcode': '402'})
        #         jwt_token = MyJwt().encode({'id': user.id, 'email': user.email})
        #         return self.finish({'msg': '登录成功', 'errcode': '0', 'email': user.email, 'token': jwt_token})
        #
        #     except Exception as e:
        #     # 限制五分钟内 最多失败登录五次  redis 版本
        #         num = self.application.redis.get(key)  # 获取失败次数   redis 版本
        #
        #         if not num:  # 如果没有失败次数 说明是五分钟内第一次失败
        #             self.application.redis.set(key, 1, ex=60 * 5)  # 存入redis 失败次数为1 并设置过期时间5分钟
        #         else:
        #             if int(num) >= 5:   # 失败次数等于5  封禁0
        #                 self.application.redis.set(ban_key,'封禁',ex=60 * 30)  # 将该邮箱存三十分钟 代表封禁状态
        #                 return self.finish({'msg': '该账号已被封禁30分钟', 'errcode': '400'})
        #             else:     # 失败次数小于5     将失败次数+1
        #                 self.application.redis.incr(key)
        #
        #         return self.finish({'msg': '账号或密码错误', 'errcode': '400'})



# gitee 三方登录 具体功能类
class GiteeProvider(IdProvider):
    def __init__(self):
        self.client_id = 'f04e0838f43bfec41c508be48514a06c9f2a9238388f19aa922debe3bb151e40'
        self.redirect_uri = 'http://localhost:8000/gitee_back/'
        self.client_secret = 'e56873e517d2b62a5e9f8fd335b3aba93b4e31cd6577219023e3288ba65c407e'
        self.database = peewee_async.Manager(database)

    def get_url(self):   # 拼接扫码路由
        return 'https://gitee.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code'%(self.client_id,self.redirect_uri)

    def get_token(self,code):   # 使用code 获取 token
        data = {'grant_type':'authorization_code','code':code,'client_id':self.client_id,'redirect_uri':self.redirect_uri,'client_secret':self.client_secret}
        url = 'https://gitee.com/oauth/token'
        res = requests.post(url,data=data)   # 发送 post请求 并携带参数
        acctoken = res.json().get('access_token')
        return acctoken

    def get_user(self,token,uid=0):  # 使用token 获取用户信息
        data = {'access_token':token}
        url = 'https://gitee.com/api/v5/user'
        res = requests.get(url,data=data, timeout=30)
        return {'email':res.json()['email'],'avtar':res.json()['avatar_url']}

    async def save_user(self,user_info):
        try:
            user = await self.database.get(User_Model.select().where((User_Model.email==user_info['email'])&(User_Model.cate==1)))
        except Exception as e:
            print(e)
            user = await self.database.create(User_Model,email=user_info['email'],password='*',cate=1,state=1,avtar=user_info['avtar'])
        # user.avtar = user_info['avtar']
        # await self.database.update(user)
        return user
# gitee 三方登录 视图类
class Gitee(BaseHandler):
    def __init__(self,*args, **kwargs):
        super(Gitee, self).__init__(*args, **kwargs)
        self.gitee = SimpleFactory().product('gitee')
    async def post(self):
        url = self.gitee.get_url()
        return self.finish({'errcode':0,'url':url})
    async def get(self):
        code = self.get_argument('code',None)
        acctoken = self.gitee.get_token(code)
        user_info = self.gitee.get_user(acctoken)
        user = await self.gitee.save_user(user_info)
        token = MyJwt().encode({'id': user.id,'email':user.email})
        self.redirect('http://localhost:8080/tranfer?email=%s&token=%s'%(user.email,token))

# 微博三方登录  实现具体功能类
class SinlangProvider(IdProvider):
    def __init__(self):
        self.client_id = 3440988304
        self.client_secret = '15dde1e8af983da29490e5ac5de10f55'
        self.redirect_uri='http://127.0.0.1:8000/weibo_back/'
        self.database = peewee_async.Manager(database)

    def get_url(self):
        url = f'https://api.weibo.com/oauth2/authorize?client_id={self.client_id}&response_type=code&redirect_uri={self.redirect_uri}'
        return url

    def get_token(self,code):
        data = {'client_id':self.client_id,'client_secret':self.client_secret,'grant_type':'authorization_code','code':code,'redirect_uri':self.redirect_uri}
        url = 'https://api.weibo.com/oauth2/access_token'
        res = requests.post(url,data=data,timeout=30)
        return res.json()['access_token'],res.json()['uid']

    def get_user(self,token,uid):
        data = {'access_token':token,'uid':uid}
        url = 'https://api.weibo.com/2/users/show.json'
        res = requests.get(url, params=data, timeout=30)
        return {'name':res.json()['screen_name'],'avtar':res.json()['profile_image_url']}

    async def save_user(self,user_info):
        try:
            user = await self.database.get(User_Model.select().where((User_Model.email==user_info['name']+'@qq.com')&(User_Model.cate==2)))
        except Exception as e:
            print(e)
            user = await self.database.create(User_Model,email=user_info['name']+'@qq.com',password='*',cate=2,state=1,avtar=user_info['avtar'])
        # user.avtar = user_info['avtar']
        # await self.database.update(user)
        return user

# 微博登录 视图类   # 微博三方登录
class Sina(BaseHandler):

    def __init__(self,*args,**kwargs):
        super(Sina,self).__init__(*args,**kwargs)
        self.sina = SimpleFactory().product('sina')  # 新浪的功能类

    async def post(self):
        # 获取url
        url = self.sina.get_url()
        return self.finish({'errcode':0,'url':url})   # 返回给前端url

    async def get(self):
        code = self.get_argument('code',None)
        acctoken,uid = self.sina.get_token(code)  # 获取token与uid
        user_info= self.sina.get_user(acctoken,uid)   # 获取用户信息
        user = await self.sina.save_user(user_info)
        token = MyJwt().encode({'id':user.id,'email':user.email})
        self.redirect('http://localhost:8080/tranfer?email=%s&token=%s' % (user.email, token))


class User_info(BaseHandler):
    @jwt_token
    async def get(self):
        # avtar = self._cuser.avtar
        # if 'http' not in self._cuser.avtar:
        #     avtar = str(self._cuser.id)+'/'+avtar

        res = {'errcode':'0','avtar':self._cuser.avtar, 'msg':'获取成功','cate':self._cuser.cate}
        return self.finish(res)
class AtuserHandler(BaseHandler):    #   @ 用户信息
    @property
    def get_url(self):
        return 'http://localhost:8000'
    @jwt_token
    async def get(self):
        uid = self.get_argument('uid',None)
        if uid:
            user = await self.application.objects.get(User_Model.select().where(User_Model.id==uid))
            data = model_to_dict(user)
            if 'http' not in data['avtar']:
                data['avtar'] = self.get_url + data['avtar'][1:]
        else:
            users = await self.application.objects.execute(User_Model.select())
            data = []
            for i in users:
                dict1={'name':i.email}
                data.append(dict1)
        return self.finish({'errcode':'0', 'msg':'获取成功','data':data})
urlpatterns = [
    url('/user/register',UserHandler),
    url('/user/login',UserLogin),
    url('/imagecode/',ImageCode),
    url('/gitee_back/',Gitee),
    url('/weibo_back/',Sina),
    url('/user_info',User_info),
    url('/upload/',FileUpload),
    url('/file/',FileHandler),
    url('/usermanage/',UserManage),
    url('/node/',NodeHandler),
    url('/access/',AccessHandler),
    url('/role/',RoleHandler),
    url('/atuser/',AtuserHandler),

]

